<template>
    <div class="pt-6 sm:pt-8">
        <div class="sm:flex sm:items-center">
            <div class="sm:flex-auto">
                <h1 class="text-base font-semibold text-gray-900 dark:text-gray-100">用户管理</h1>
                <p class="mt-2 text-sm text-gray-700 dark:text-gray-300">管理系统中的所有用户，包括用户名、角色、状态等信息。</p>
            </div>
            <div class="mt-4 sm:mt-0 sm:ml-16 sm:flex-none">
                <button type="button"
                    class="block px-3 py-2 text-sm font-semibold text-center text-white bg-indigo-600 rounded-md shadow-xs hover:bg-indigo-500 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600"
                    @click.stop="openCreateModal">添加用户</button>
            </div>
        </div>
        <div class="relative mt-8 -mx-4 bg-white shadow-xs dark:bg-gray-800 rounded-xl sm:-mx-0">
            <div class="overflow-x-auto">
                <table
                    class="w-full min-w-full divide-y divide-gray-100 table-auto dark:text-gray-300 dark:divide-gray-700/60">
                    <thead
                        class="text-xs font-semibold text-gray-500 uppercase border-t border-b border-gray-100 dark:text-gray-400 bg-gray-50 dark:bg-gray-900/20 dark:border-gray-700/60">
                                                <tr>
                            <th scope="col" class="w-1/3 px-2 py-3 text-left first:pl-5 last:pr-5 whitespace-nowrap">
                                用户名
                            </th>
                            <th scope="col"
                                class="w-1/6 hidden px-2 py-3 text-center first:pl-5 last:pr-5 whitespace-nowrap sm:table-cell">
                                角色
                            </th>
                            <th scope="col"
                                class="w-1/6 hidden px-2 py-3 text-center first:pl-5 last:pr-5 whitespace-nowrap sm:table-cell">
                                状态
                            </th>
                            <th scope="col" class="w-1/3 px-2 py-3 text-center first:pl-5 last:pr-5 whitespace-nowrap">
                                操作
                            </th>
                        </tr>
                    </thead>
                    <tbody class="text-sm divide-y divide-gray-100 dark:divide-gray-700/60">
                        <tr v-for="user in users" :key="user.id">
                                                        <td
                                class="w-1/3 px-2 py-4 font-medium text-left text-gray-800 first:pl-5 last:pr-5 whitespace-nowrap dark:text-gray-100">
                                {{ user.username }}
                                <dl class="font-normal lg:hidden">
                                    <dd class="mt-1 text-gray-500 truncate dark:text-gray-400 sm:hidden">
                                        <span :class="roleClass(user.role)">{{ getRoleText(user.role) }}</span>
                                    </dd>
                                </dl>
                            </td>
                            <td
                                class="w-1/6 hidden px-2 py-4 text-center text-gray-500 first:pl-5 last:pr-5 whitespace-nowrap dark:text-gray-400 sm:table-cell">
                                <span :class="roleClass(user.role)">{{ getRoleText(user.role) }}</span>
                            </td>
                            <td
                                class="w-1/6 hidden px-2 py-4 text-center text-gray-500 first:pl-5 last:pr-5 whitespace-nowrap dark:text-gray-400 sm:table-cell">
                                <span :class="statusClass(user.disabled)">
                                    {{ user.disabled ? "已禁用" : "正常" }}
                                </span>
                            </td>
                            <td class="w-1/3 px-2 py-4 text-center first:pl-5 last:pr-5 whitespace-nowrap">
                                <div class="flex flex-wrap justify-center gap-2">
                                    <button type="button"
                                        class="text-indigo-600 hover:text-indigo-900 dark:text-indigo-400 dark:hover:text-indigo-300"
                                        @click.stop="openEditModal(user)">编辑</button>
                                    <button v-if="user.username !== 'admin'" type="button"
                                        class="text-yellow-600 hover:text-yellow-900 dark:text-yellow-400 dark:hover:text-yellow-300"
                                        :class="user.disabled ? 'text-green-600 hover:text-green-900 dark:text-green-400 dark:hover:text-green-300' : ''"
                                        @click.stop="toggleUserStatus(user)">
                                        {{ user.disabled ? '启用' : '禁用' }}
                                    </button>
                                    <button v-if="user.username !== 'admin'" type="button"
                                        class="text-red-600 hover:text-red-900 dark:text-red-400 dark:hover:text-red-300"
                                        @click.stop="confirmDelete(user)">删除</button>
                                </div>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- 创建/编辑用户模态框 -->
        <ModalBasic id="user-modal" :modalOpen="showEditModal" :title="editMode ? '编辑用户' : '新增用户'">
            <div class="px-5 py-4">
                <div class="space-y-3">
                    <div>
                        <label class="block mb-1 text-sm font-medium" for="username">用户名 <span
                                class="text-red-500">*</span></label>
                        <input id="username" class="w-full px-2 py-1 form-input" type="text" v-model="userForm.username"
                            :disabled="editMode" required />
                    </div>
                    <div v-if="!editMode">
                        <label class="block mb-1 text-sm font-medium" for="password">密码 <span
                                class="text-red-500">*</span></label>
                        <input id="password" class="w-full px-2 py-1 form-input" type="password" v-model="userForm.password"
                            required />
                    </div>
                    <div v-if="editMode">
                        <label class="block mb-1 text-sm font-medium" for="new_password">新密码</label>
                        <input id="new_password" class="w-full px-2 py-1 form-input" type="password" v-model="userForm.new_password"
                            placeholder="留空则不修改密码" />
                    </div>
                    <div v-if="editMode">
                        <label class="block mb-1 text-sm font-medium" for="confirm_password">确认新密码</label>
                        <input id="confirm_password" class="w-full px-2 py-1 form-input" type="password" v-model="userForm.confirm_password"
                            placeholder="再次输入新密码" />
                    </div>

                    <div>
                        <label class="block mb-1 text-sm font-medium" for="role">角色</label>
                        <select id="role" class="w-full px-2 py-1 form-select" v-model="userForm.role">
                            <option value="user">普通用户</option>
                            <option value="admin">管理员</option>
                        </select>
                    </div>
                    <div>
                        <label class="flex items-center gap-2">
                            <input type="checkbox" class="w-4 h-4 text-indigo-600 focus:ring-0 focus:outline-none"
                                v-model="userForm.is_active">
                            <span class="text-sm font-medium">启用账户</span>
                        </label>
                    </div>
                </div>
            </div>
            <div class="px-5 py-4 border-t border-gray-200 dark:border-gray-700/60">
                <div class="flex flex-wrap justify-end space-x-2">
                    <button
                        class="text-gray-800 border-gray-200 btn-sm dark:border-gray-700/60 hover:border-gray-300 dark:hover:border-gray-600 dark:text-gray-300"
                        @click="closeModal">
                        取消</button>
                    <button
                        class="text-gray-100 bg-gray-900 btn-sm hover:bg-gray-800 dark:bg-gray-100 dark:text-gray-800 dark:hover:bg-white"
                        @click="handleSubmit">
                        {{ editMode ? '保存' : '创建' }}</button>
                </div>
            </div>
        </ModalBasic>

        <!-- 删除确认模态框 -->
        <ModalBasic id="delete-modal" :modalOpen="showDeleteModal" title="确认删除">
            <div class="px-5 py-4">
                <div class="text-sm">
                    <div class="mb-3 font-medium text-gray-800 dark:text-gray-100">
                        确定要删除用户 "{{ userToDelete?.username }}" 吗？此操作无法撤销。
                    </div>
                </div>
            </div>
            <div class="px-5 py-4 border-t border-gray-200 dark:border-gray-700/60">
                <div class="flex flex-wrap justify-end space-x-2">
                    <button
                        class="text-gray-800 border-gray-200 btn-sm dark:border-gray-600 hover:border-gray-300 dark:hover:border-gray-500 dark:text-gray-100 dark:hover:text-gray-300"
                        @click="showDeleteModal = false">
                        取消
                    </button>
                    <button class="text-white bg-red-600 btn-sm dark:bg-red-500 hover:bg-red-700 dark:hover:bg-red-600"
                        @click="deleteUser">
                        确认删除
                    </button>
                </div>
            </div>
        </ModalBasic>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, computed } from "vue";
import { authApi } from "../api/authService";
import type { UserResponse } from "../api/authService";
import ModalBasic from "../components/ModalBasic.vue"

const users = ref<UserResponse[]>([]);
const showEditModal = ref(false);
const showDeleteModal = ref(false);
const editMode = ref(false);
const currentId = ref<number | null>(null);
const userToDelete = ref<UserResponse | null>(null);

const userForm = reactive({
    username: "",
    password: "",
    new_password: "",
    confirm_password: "",
    role: "user" as "user" | "admin",
    is_active: true,
    show_password_fields: false,
});

const fetchUsers = async () => {
    try {
        const result = await authApi.getUsers();
        users.value = result;
    } catch (error) {
        console.error("获取用户列表失败：", error);
    }
};

const getRoleText = (role: string) => {
    return role === "admin" ? "管理员" : "普通用户";
};

const roleClass = (role: string) => {
    return {
        "text-purple-600 dark:text-purple-400 font-medium": role === "admin",
        "text-blue-600 dark:text-blue-400": role === "user"
    };
};

const statusClass = (disabled: boolean) => {
    return {
        "text-green-600 dark:text-green-400": !disabled,
        "text-red-600 dark:text-red-400": disabled
    };
};

const openCreateModal = () => {
    editMode.value = false;
    resetForm();
    showEditModal.value = true;
};

const openEditModal = (user: UserResponse) => {
    editMode.value = true;
    currentId.value = user.id;
    Object.assign(userForm, {
        username: user.username,
        password: "",
        new_password: "",
        confirm_password: "",
        role: user.role,
        is_active: !user.disabled,
        show_password_fields: false
    });
    showEditModal.value = true;
};

const confirmDelete = (user: UserResponse) => {
    if (user.username === 'admin') {
        alert('无法删除顶级管理员账户');
        return;
    }
    userToDelete.value = user;
    showDeleteModal.value = true;
};

const deleteUser = async () => {
    if (!userToDelete.value) return;

    try {
        await authApi.deleteUser(userToDelete.value.id);
        await fetchUsers();
        showDeleteModal.value = false;
        userToDelete.value = null;
    } catch (error) {
        console.error("删除用户失败：", error);
    }
};

const toggleUserStatus = async (user: UserResponse) => {
    try {
        await authApi.updateUserStatus(user.id, !user.disabled);
        await fetchUsers();
    } catch (error) {
        console.error("更新用户状态失败：", error);
    }
};

const resetForm = () => {
    Object.assign(userForm, {
        username: "",
        password: "",
        new_password: "",
        confirm_password: "",
        role: "user" as "user" | "admin",
        is_active: true,
        show_password_fields: false
    });
    currentId.value = null;
};

const togglePasswordFields = () => {
    userForm.show_password_fields = !userForm.show_password_fields;
    if (!userForm.show_password_fields) {
        userForm.new_password = "";
        userForm.confirm_password = "";
    }
};

const closeModal = () => {
    showEditModal.value = false;
    resetForm();
};

const handleSubmit = async () => {
    try {
        if (editMode.value && currentId.value) {
            // 编辑模式 - 验证密码修改
            if (userForm.show_password_fields && userForm.new_password) {
                if (userForm.new_password !== userForm.confirm_password) {
                    alert('新密码与确认密码不匹配');
                    return;
                }
                if (userForm.new_password.length < 6) {
                    alert('密码长度至少6位');
                    return;
                }
            }
            
            // 这里需要后端提供更新用户信息的接口
            console.log("编辑用户:", currentId.value, userForm);
            // await authApi.updateUser(currentId.value, userForm);
        } else {
            // 创建模式
            await authApi.createUser({
                username: userForm.username,
                password: userForm.password,
                role: userForm.role,
                disabled: !userForm.is_active
            });
        }
        await fetchUsers();
        closeModal();
    } catch (error) {
        console.error("保存失败：", error);
    }
};

onMounted(() => {
    fetchUsers();
});
</script>
